<?php
class ApiGiftController extends ApiController
{
  public function indexAction()
  {
    $giftModel = $this->getModel('gift');
    $page = max(intval($this->req->getQueryTrim('page', 1)), 1);
    $rows = intval($this->req->getQueryTrim('rows', 15));
    return $this->okReturn(['list' => $giftModel->getGiftsList([
     'status' => Gift::IS_ONLINE
    ], $page, $rows)]);
  }

  public function exchangeAction()
  {
    if ($this->req->isPost()) {
     if (($gift = $this->getModel('gift')->getGift($this->req->getPostTrim('gift_id')))
       && $gift->status == Gift::IS_ONLINE ) {
        //检查该礼品是否兑换过
        if ($this->getModel('mysql')->query('select count(*) from `players_gifts`  where `player_id` = ? and `gift_id` = ?', [
          $this->account->player_id, $gift->gift_id
        ])->field()) {
          return $this->okReturn(['error' => 1, 'message' => '您已经兑换过该商品，可以在兑换历史找到喔！']);
        }
        if ($gift->flowers > $this->account->flowers) { return $this->okReturn(['error' => 1, 'message' => '非常抱歉，您的鲜花数量还不足以兑换这个奖品呢，请继续加油经营店铺，以获得更多的鲜花哦~']); }
        if ($gift->type == Gift::IS_PRODUCT && $gift->amount <= 0) { return $this->okReturn(['error' => 2, 'message' => '您来迟了，礼品已经兑完了！！']);}
        if ($gift->type == Gift::IS_PRODUCT && empty($this->account->realname)) { return $this->okReturn(['error' => 3, 'message' => '兑换前请先填写个人资料']); }
        return $this->okReturn(['error' => 0, 'result' => boolval($this->account->exchange($gift->gift_id))]);
      }
    }
    return $this->okReturn(['error' => 4, 'message' => '礼品不存在']);
  }

  public function exchangeListAction()
  {
    $giftModel = $this->getModel('gift');
    $page = max(intval($this->req->getQueryTrim('page', 1)), 1);
    $rows = intval($this->req->getQueryTrim('rows', 15));
    return $this->okReturn(['list' => $giftModel->getPlayerGiftsList([
      'player_id' => $this->account->player_id
    ], $page, $rows), 'count' => $giftModel->getPlayerGiftsCount([
      'player_id' => $this->account->player_id
    ])]);
  }

}